package cn.samler.diandi.api.handler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;


@MappedTypes(JSONObject.class)
@MappedJdbcTypes(JdbcType.VARCHAR)
public class JsonTypeHandler<T extends Object> extends BaseTypeHandler<T> {

    private final Class<T> clazz;
    private final ObjectMapper objectMapper = new ObjectMapper();

    public JsonTypeHandler(Class<T> clazz) {
        if (clazz == null) {
            throw new IllegalArgumentException("Type argument cannot be null");
        }
        this.clazz = clazz;
    }

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, T parameter, JdbcType jdbcType) throws SQLException {
        try {
            ps.setString(i, objectMapper.writeValueAsString(parameter));
        } catch (Throwable e) {
            ps.setString(i, JSON.toJSONString(parameter));
        }
    }

    /**
     * 根据列名，获取可以为空的结果
     */
    @Override
    public T getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String sqlJson = rs.getString(columnName);
        if (StringUtils.isNotBlank(sqlJson)) {
            try {
                return objectMapper.readValue(sqlJson, clazz);
            } catch (Throwable e) {
                return JSONObject.parseObject(sqlJson, clazz);
            }
        }

        return null;
    }

    /**
     * 根据列索引，获取可以为空的结果
     */
    @Override
    public T getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String sqlJson = rs.getString(columnIndex);
        if (StringUtils.isNotBlank(sqlJson)) {
            try {
                return objectMapper.readValue(sqlJson, clazz);
            } catch (Throwable e) {
                return JSONObject.parseObject(sqlJson, clazz);
            }
        }
        return null;
    }

    @Override
    public T getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        String sqlJson = cs.getString(columnIndex);
        if (StringUtils.isNotBlank(sqlJson)) {
            try {
                return objectMapper.readValue(sqlJson, clazz);
            } catch (Throwable e) {
                return JSONObject.parseObject(sqlJson, clazz);
            }
        }
        return null;
    }
}
